package org.hyh.core.security.handler;

import com.alibaba.fastjson.JSON;
import org.hyh.core.model.entity.SysUser;
import org.hyh.core.model.properties.JwtProperties;
import org.hyh.core.model.vo.ResultVo;
import org.hyh.core.utils.JwtUtils;
import org.hyh.core.utils.ResponseUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.header.Header;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @auther :hyh
 * @desc :
 * @date :2020/7/12
 */
public class HandlerWhenLoginSuccess  implements AuthenticationSuccessHandler {

    /**
     *  登录成功后，获取用户名和id, 生成token 返回。
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //生成token
        SysUser principal = (SysUser) authentication.getPrincipal();
        String token = JwtUtils.getToken(principal);
        response.addHeader(JwtProperties.TOKEN_HEADER_NAME, token);
        ResultVo resultVo = ResultVo.buildOkData("认证成功!");
        ResponseUtils.resetAndResponseToClient(response,resultVo,true);

    }
}
